/**
 * 封装了一些dom操作
 */

/**
 * 为dom对象添加类样式
 * @param el
 * @param className
 * @return {null}
 */
export function addClass (el, className) {
  if (hasClass(el, className)) {
    return null
  }
  let clazzs = el.className
  clazzs = clazzs.split(' ')
  clazzs.push(className)
  el.className = clazzs.join(' ')
}

/**
 * 判断dom对象是否具有指定类样式
 * @param el
 * @param className
 * @return {boolean}
 */
export function hasClass (el, className) {
  let reg = new RegExp('(^|\\s)' + className + '($|\\s)')
  return reg.test(el.className)
}

/**
 * get or set Dom attribute
 * @param el
 * @param name
 * @param val
 * @return {void|*|ASTElement|ASTText|ASTExpression|string}
 */
export function dataAttr (el, name, val) {
  const prefix = 'data-'
  name = prefix + name
  if (val) {
    return el.setAttribute(name, val)
  } else {
    return el.getAttribute(name)
  }
}

// 判断浏览器类别
let elementStyle = document.createElement('div').style
let vendor = (() => {
  let transformName = {
    webkit: 'webkitTransform',
    Moz: 'MozTransform',
    O: 'OTransform',
    ms: 'msTranform',
    standard: 'transform'
  }
  for (let key in transformName) {
    if (elementStyle[transformName[key]] !== undefined) {
      return key
    }
  }
  return false
})()

/**
 * 获取不同浏览器对应的Tranform属性名:MozTransform
 * @param style
 * @return {string|boolean|*}
 */
export function prefixStyle (style) {
  if (vendor === false) {
    return false
  }
  if (vendor === 'standard') {
    return style
  }
  return vendor + style.charAt(0).toUpperCase() + style.substring(1)
}
